package cn.edu.nju.software.zp13.client.assignment3.seeder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

import cn.edu.nju.software.zp13.client.assignment3.xmlNodeEntity.CourseScore;
import cn.edu.nju.software.zp13.client.assignment3.xmlNodeEntity.Department;
import cn.edu.nju.software.zp13.client.assignment3.xmlNodeEntity.Profile;
import cn.edu.nju.software.zp13.client.assignment3.xmlNodeEntity.Student;
import cn.edu.nju.software.zp13.client.assignment3.xmlNodeEntity.util.Gender;


/**
 * This class is to generate several student object which data are defined in
 * student
 * 
 * @author Ivan
 *
 */
public class StudentGenerator {
	private static List<Student> students;
	private static final String studentFilePath;

	static {
		students = new LinkedList<>();
		studentFilePath = System.getProperty("user.dir") + "/src/cn/edu/nju/software/zp13/client/assignment3/seeder/student";
		readStudentFile(studentFilePath);
	}

	/**
	 * generate student based on id and name
	 * 
	 * @param studentId
	 * @param studentName
	 * @return
	 */
	public static Student[] run() {
		Student[] studentArray = new Student[students.size()];
		for (int i = 0; i < studentArray.length; i++) {
			Student s = students.get(i);
			studentArray[i] = new Student();
			studentArray[i].setId(s.getId());
			Profile p = s.getProfile();
			p.setDepartment(new Department("1250", "software"));
			studentArray[i].setProfile(p);
			CourseScore[] cs = CourseScoreGenerator.run(5, s.getId());
			studentArray[i].setCs(cs);
		}
		return studentArray;
	}

	private static void readStudentFile(String filePath) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(new File(filePath)));
			String line = "";
			while ((line = br.readLine()) != null) {
				String seperator=" ";
				if (line.startsWith("##")) {
					continue;
				}
				String[] parts = line.split(seperator);
				if (parts.length != 4) {
					continue;
				}
				Student s = new Student();
				s.setId(parts[0]);
				Profile p = new Profile();
				p.setName(parts[1]);
				p.setGender(Gender.valueOf(parts[2]));
				p.setBirthday(LocalDate.parse(parts[3], DateTimeFormatter.ISO_DATE));
				s.setProfile(p);
				students.add(s);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
			if (br != null) {
				try {
					br.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

		}

	}
}

